{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Using TensorFlow backend.\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'channels_last'"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from __future__ import absolute_import\n",
    "from __future__ import division\n",
    "from __future__ import print_function\n",
    "\n",
    "import argparse\n",
    "import sys\n",
    "import tensorflow as tf\n",
    "import numpy as np\n",
    "\n",
    "from tensorflow.examples.tutorials.mnist import input_data\n",
    "\n",
    "\n",
    "\n",
    "from keras.layers.core import Dense, Flatten, Dropout\n",
    "from keras.layers.convolutional import Conv2D\n",
    "from keras.layers.pooling import MaxPooling2D\n",
    "\n",
    "from keras import backend as K\n",
    "\n",
    "\n",
    "K.image_data_format() "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Extracting ./mnist/input_data\\train-images-idx3-ubyte.gz\n",
      "Extracting ./mnist/input_data\\train-labels-idx1-ubyte.gz\n",
      "Extracting ./mnist/input_data\\t10k-images-idx3-ubyte.gz\n",
      "Extracting ./mnist/input_data\\t10k-labels-idx1-ubyte.gz\n"
     ]
    }
   ],
   "source": [
    "data_dir = './mnist/input_data'\n",
    "mnist = input_data.read_data_sets(data_dir, one_hot=True)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "starting.......\n",
      "epoch:0 train_accu:0.918455 test_accu:0.969600\n",
      "epoch:1 train_accu:0.986782 test_accu:0.982300\n",
      "epoch:2 train_accu:0.987836 test_accu:0.984000\n",
      "epoch:3 train_accu:0.988600 test_accu:0.977500\n",
      "epoch:4 train_accu:0.989345 test_accu:0.979100\n",
      "epoch:5 train_accu:0.988346 test_accu:0.974000\n",
      "epoch:6 train_accu:0.989309 test_accu:0.986400\n",
      "epoch:7 train_accu:0.989327 test_accu:0.982200\n",
      "epoch:8 train_accu:0.989873 test_accu:0.984400\n",
      "epoch:9 train_accu:0.991345 test_accu:0.980900\n",
      "epoch:10 train_accu:0.990473 test_accu:0.984800\n",
      "epoch:11 train_accu:0.990273 test_accu:0.988400\n",
      "epoch:12 train_accu:0.990891 test_accu:0.984700\n",
      "epoch:13 train_accu:0.991709 test_accu:0.981100\n",
      "epoch:14 train_accu:0.991564 test_accu:0.982900\n",
      "epoch:15 train_accu:0.991254 test_accu:0.984800\n",
      "epoch:16 train_accu:0.991091 test_accu:0.985400\n",
      "epoch:17 train_accu:0.992527 test_accu:0.987400\n",
      "epoch:18 train_accu:0.991655 test_accu:0.981800\n",
      "epoch:19 train_accu:0.992327 test_accu:0.986400\n",
      "epoch:20 train_accu:0.992109 test_accu:0.988100\n",
      "epoch:21 train_accu:0.992073 test_accu:0.989500\n",
      "epoch:22 train_accu:0.993309 test_accu:0.983500\n",
      "epoch:23 train_accu:0.992218 test_accu:0.989300\n",
      "epoch:24 train_accu:0.993109 test_accu:0.987500\n",
      "epoch:25 train_accu:0.992854 test_accu:0.989100\n",
      "epoch:26 train_accu:0.993200 test_accu:0.989300\n",
      "epoch:27 train_accu:0.992655 test_accu:0.988600\n",
      "epoch:28 train_accu:0.993982 test_accu:0.989100\n",
      "epoch:29 train_accu:0.993673 test_accu:0.988200\n",
      "epoch:30 train_accu:0.993145 test_accu:0.990000\n",
      "epoch:31 train_accu:0.993927 test_accu:0.989000\n",
      "epoch:32 train_accu:0.993891 test_accu:0.990400\n",
      "epoch:33 train_accu:0.993945 test_accu:0.988600\n",
      "epoch:34 train_accu:0.994164 test_accu:0.989500\n",
      "epoch:35 train_accu:0.993509 test_accu:0.989100\n",
      "epoch:36 train_accu:0.993764 test_accu:0.988300\n",
      "epoch:37 train_accu:0.994800 test_accu:0.988600\n",
      "epoch:38 train_accu:0.994236 test_accu:0.990300\n",
      "epoch:39 train_accu:0.994745 test_accu:0.989600\n",
      "epoch:40 train_accu:0.994418 test_accu:0.989500\n",
      "epoch:41 train_accu:0.994655 test_accu:0.989300\n",
      "epoch:42 train_accu:0.995109 test_accu:0.989000\n",
      "epoch:43 train_accu:0.994764 test_accu:0.990400\n",
      "epoch:44 train_accu:0.995164 test_accu:0.988800\n",
      "epoch:45 train_accu:0.994636 test_accu:0.987300\n",
      "epoch:46 train_accu:0.995327 test_accu:0.987900\n",
      "epoch:47 train_accu:0.995236 test_accu:0.990000\n",
      "epoch:48 train_accu:0.996000 test_accu:0.989800\n",
      "epoch:49 train_accu:0.995564 test_accu:0.992000\n",
      "epoch:50 train_accu:0.995818 test_accu:0.990200\n",
      "epoch:51 train_accu:0.995436 test_accu:0.991300\n",
      "epoch:52 train_accu:0.995927 test_accu:0.991900\n",
      "epoch:53 train_accu:0.996109 test_accu:0.990000\n",
      "epoch:54 train_accu:0.995582 test_accu:0.989700\n",
      "epoch:55 train_accu:0.995364 test_accu:0.990300\n",
      "epoch:56 train_accu:0.995709 test_accu:0.991800\n",
      "epoch:57 train_accu:0.995727 test_accu:0.991200\n",
      "epoch:58 train_accu:0.996182 test_accu:0.990700\n",
      "epoch:59 train_accu:0.996164 test_accu:0.989300\n",
      "epoch:60 train_accu:0.995745 test_accu:0.990400\n",
      "epoch:61 train_accu:0.996109 test_accu:0.991500\n",
      "epoch:62 train_accu:0.996200 test_accu:0.991200\n",
      "epoch:63 train_accu:0.996418 test_accu:0.991000\n",
      "epoch:64 train_accu:0.996345 test_accu:0.991200\n",
      "epoch:65 train_accu:0.996709 test_accu:0.991100\n",
      "epoch:66 train_accu:0.996673 test_accu:0.991000\n",
      "epoch:67 train_accu:0.996873 test_accu:0.989900\n",
      "epoch:68 train_accu:0.996545 test_accu:0.989500\n",
      "epoch:69 train_accu:0.996727 test_accu:0.990900\n",
      "epoch:70 train_accu:0.996818 test_accu:0.989700\n",
      "epoch:71 train_accu:0.997055 test_accu:0.991900\n",
      "epoch:72 train_accu:0.997200 test_accu:0.991600\n",
      "epoch:73 train_accu:0.996982 test_accu:0.991100\n",
      "epoch:74 train_accu:0.996982 test_accu:0.990900\n",
      "epoch:75 train_accu:0.997364 test_accu:0.990800\n",
      "epoch:76 train_accu:0.996855 test_accu:0.991700\n",
      "epoch:77 train_accu:0.997400 test_accu:0.992100\n",
      "epoch:78 train_accu:0.996927 test_accu:0.990700\n",
      "epoch:79 train_accu:0.997418 test_accu:0.991700\n",
      "epoch:80 train_accu:0.997600 test_accu:0.991800\n",
      "epoch:81 train_accu:0.997218 test_accu:0.992100\n",
      "epoch:82 train_accu:0.997364 test_accu:0.992600\n",
      "epoch:83 train_accu:0.997236 test_accu:0.991200\n",
      "epoch:84 train_accu:0.997545 test_accu:0.992400\n",
      "epoch:85 train_accu:0.997291 test_accu:0.991700\n",
      "epoch:86 train_accu:0.997564 test_accu:0.992200\n",
      "epoch:87 train_accu:0.997564 test_accu:0.991800\n",
      "epoch:88 train_accu:0.997782 test_accu:0.992500\n",
      "epoch:89 train_accu:0.997564 test_accu:0.991800\n",
      "epoch:90 train_accu:0.997891 test_accu:0.991100\n",
      "epoch:91 train_accu:0.997691 test_accu:0.991800\n",
      "epoch:92 train_accu:0.997927 test_accu:0.992300\n",
      "epoch:93 train_accu:0.997654 test_accu:0.991300\n",
      "epoch:94 train_accu:0.998109 test_accu:0.992200\n",
      "epoch:95 train_accu:0.997727 test_accu:0.992300\n",
      "epoch:96 train_accu:0.998073 test_accu:0.992400\n",
      "epoch:97 train_accu:0.997982 test_accu:0.991900\n",
      "epoch:98 train_accu:0.997927 test_accu:0.992500\n",
      "epoch:99 train_accu:0.998273 test_accu:0.991800\n"
     ]
    }
   ],
   "source": [
    "# Define loss and optimizer\n",
    "x = tf.placeholder(tf.float32, [None, 784])\n",
    "y_ = tf.placeholder(tf.float32, [None, 10])\n",
    "learning_rate = tf.placeholder(tf.float32)\n",
    "with tf.name_scope('reshape'):\n",
    "  x_image = tf.reshape(x, [-1, 28, 28, 1])\n",
    "\n",
    "#kernel和bias初始化\n",
    "w_init = tf.truncated_normal_initializer(stddev=0.1, seed=9)\n",
    "b_init = tf.constant_initializer(0.1)\n",
    "\n",
    "#卷积\n",
    "net = Conv2D(32, kernel_size=[5,5], strides=[1,1],activation='relu',\n",
    "                 padding='same',\n",
    "                input_shape=[28,28,1],\n",
    "                kernel_initializer=w_init,\n",
    "                bias_initializer=b_init)(x_image)\n",
    "#池化\n",
    "net = MaxPooling2D(pool_size=[2,2])(net)\n",
    "#卷积\n",
    "net = Conv2D(64, kernel_size=[5,5], strides=[1,1],activation='relu',\n",
    "                padding='same',\n",
    "                kernel_initializer=w_init,\n",
    "                bias_initializer=b_init)(net)\n",
    "#池化\n",
    "net = MaxPooling2D(pool_size=[2,2])(net)\n",
    "#卷积\n",
    "net = Conv2D(128, kernel_size=[3,3], strides=[1,1],activation='relu',\n",
    "                padding='same',\n",
    "                kernel_initializer=w_init,\n",
    "                bias_initializer=b_init)(net)\n",
    "net = Flatten()(net)\n",
    "#net = Dense(2000, activation='tanh')(net)\n",
    "#net = Dropout(0.5)(net)\n",
    "#net = Dense(1024, activation='relu',\n",
    "#                kernel_initializer=w_init,\n",
    "#                bias_initializer=b_init)(net)\n",
    "\n",
    "#net = Dropout(0.5)(net)\n",
    "net = Dense(10,activation='softmax')(net)\n",
    "\n",
    "#交叉熵损失函数\n",
    "from keras.objectives import categorical_crossentropy\n",
    "cross_entropy = tf.reduce_mean(categorical_crossentropy(y_, net))\n",
    "#增加l2损失\n",
    "l2_loss = tf.add_n( [tf.nn.l2_loss(w) for w in tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)] )\n",
    "total_loss = cross_entropy + 7e-4*l2_loss\n",
    "\n",
    "#训练图\n",
    "train_step = tf.train.AdamOptimizer(learning_rate).minimize(total_loss)\n",
    "\n",
    "#准确度计算图\n",
    "correct_prediction = tf.equal(tf.argmax(net, 1), tf.argmax(y_, 1))\n",
    "accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n",
    "\n",
    "sess = tf.Session()\n",
    "\n",
    "K.set_session(sess)\n",
    "\n",
    "init_op = tf.global_variables_initializer()\n",
    "sess.run(init_op)\n",
    "\n",
    "print(\"starting.......\")\n",
    "for epoch in range(100):\n",
    "    #学习率\n",
    "    lr = 0.01*(0.97**epoch)\n",
    "    #存储每一批的准确度\n",
    "    train_accu_list = []\n",
    "    test_accu_list = []\n",
    "    \n",
    "    #训练及训练集准确度计算\n",
    "    for step in range(550):\n",
    "        batch_xs, batch_ys = mnist.train.next_batch(100)\n",
    "        sess.run(train_step,feed_dict={x: batch_xs, y_: batch_ys, learning_rate:lr})\n",
    "        train_accu = sess.run(accuracy, feed_dict={x: batch_xs, y_: batch_ys})\n",
    "        train_accu_list.append(train_accu)\n",
    "    \n",
    "    #测试集准确度计算\n",
    "    for step in range(100):\n",
    "        batch_xs, batch_ys = mnist.test.next_batch(100)\n",
    "        test_accu = sess.run(accuracy, feed_dict={x: batch_xs, y_: batch_ys})\n",
    "        test_accu_list.append(test_accu)\n",
    "    \n",
    "    print(\"epoch:%d train_accu:%f test_accu:%f\"%(epoch, np.mean(train_accu_list), np.mean(test_accu_list)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
